/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.support.dev.order.notify;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @author haolw
 * @time 2018/02/25
 */
class DevOrderNotifyDispatcher extends DevAbstractDispatcher {
	private DevOrderStorageDispatcher storageDispatcher;
	private final BlockingQueue<DevOrderNotifyTask> queue;
	private final ExecutorService distributor;

	public DevOrderNotifyDispatcher() {
		queue = new DelayQueue<DevOrderNotifyTask>();
		distributor = Executors.newFixedThreadPool(8);
	}

	public void addTask(DevOrderNotifyTask task) {
		try {
			queue.offer(task, 6, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void process() {
		try {
			while (true) {
				DevOrderNotifyTask notifyTask = queue.take();
				doNotify(notifyTask);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doNotify(DevOrderNotifyTask notifyTask) {
		DevOrderTaskProcessor processor = buildTaskProcessor(notifyTask);
		distributor.execute(processor);
	}

	private DevOrderTaskProcessor buildTaskProcessor(DevOrderNotifyTask notifyTask) {
		DevOrderTaskProcessor taskProcessor = new DevOrderTaskProcessor(notifyTask);
		taskProcessor.setStorageDispatcher(storageDispatcher);
		taskProcessor.setNotifyDispatcher(this);
		return taskProcessor;
	}

	public void setStorageDispatcher(DevOrderStorageDispatcher storageDispatcher) {
		this.storageDispatcher = storageDispatcher;
	}

}
